package com.haiyou.common.util;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouyibin
 * @date 2019/6/12
 * @email Gralves@163.com
 * @desc
 */
@Component
public class RequestUtils {

    /**
     * 获取HttpServletRequest
     *
     * @return request
     * @author zhouyibin
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = null;
        try {
            request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes())
                    .getRequest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return request;
    }

    public static HashMap<String,Object> getParams(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String,Object> params=new HashMap<>();
        if (null!=parameterMap&&parameterMap.size()>0){
            parameterMap.forEach((k,v)-> params.putIfAbsent(k,v[0]));
        }
        return params;
    }

    public static HashMap<String,Object> getParams(){
        HttpServletRequest request = getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String,Object> params=new HashMap<>();
        if (null!=parameterMap&&parameterMap.size()>0){
            parameterMap.forEach((k,v)-> params.putIfAbsent(k,v[0]));
        }
        return params;
    }
}
